#include "mainwindow.h"
#include <QUrl>
#include <QDir>
#include <QSlider>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QGuiApplication>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    initLayout();
    initMedia();
    scanMedia();

    timer = new QTimer(this);

    initConnect();

    startPlayer();
}

MainWindow::~MainWindow()
{

}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == videoWidget) {
        if (event->type() == QEvent::KeyPress) {
            QKeyEvent* keyEvent = dynamic_cast<QKeyEvent*>(event);
            if (keyEvent != nullptr && keyEvent->key() == Qt::Key_Escape) {
                videoWidget->setWindowFlags(Qt::SubWindow);
                videoWidget->showNormal();
                return true;
            }
        }
        if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent* mouseEvent = dynamic_cast<QMouseEvent*>(event);
            if (mouseEvent->button() == Qt::RightButton) {
                videoWidget->setWindowFlags(Qt::SubWindow);
                videoWidget->showNormal();
                return true;
            }
        }
    }

    return QMainWindow::eventFilter(watched, event);
}

void MainWindow::initLayout()
{
    this->setGeometry(0, 0, 1280, 800);
    videoWidget = new QVideoWidget();
    listWidget = new QListWidget();
    listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    listWidget->setMinimumWidth(200);
    listWidget->setMaximumWidth(300);

    QHBoxLayout* playLayout = new QHBoxLayout();
    playWidget = new QWidget();
    playWidget->setLayout(playLayout);

    playLayout->addWidget(listWidget);
    playLayout->addWidget(videoWidget);

    videoWidget->setMinimumSize(800, 480);
    videoWidget->installEventFilter(this);
    videoWidget->setStyleSheet(R"(QVideoWidget{
                               border-image: none;
                               background:transparent;
                               border: none;
                               padding:0px 0px 0px 0px;
                               })");

    fullBtn = new QPushButton("全屏");
    prevBtn = new QPushButton("<");
    playBtn = new QPushButton("=");
    nextBtn = new QPushButton(">");
    hBoxLayout = new QHBoxLayout();
    hWidget = new QWidget();
    hWidget->setLayout(hBoxLayout);
    hBoxLayout->addWidget(fullBtn);
    hBoxLayout->addWidget(prevBtn);
    hBoxLayout->addWidget(playBtn);
    hBoxLayout->addWidget(nextBtn);

    hWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
    fullBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    prevBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
    playBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
    nextBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);

    playProgress = new QSlider();
    playProgress->setOrientation(Qt::Horizontal);  // 水平方向

    vBoxLayout = new QVBoxLayout();
    vWidget = new QWidget();
    vWidget->setLayout(vBoxLayout);
    vBoxLayout->addWidget(playWidget);
    vBoxLayout->addWidget(playProgress);
    vBoxLayout->addWidget(hWidget);

    setCentralWidget(vWidget);
}

void MainWindow::initConnect()
{
    connect(fullBtn, &QPushButton::clicked, this, &MainWindow::fullPlayer);
    connect(prevBtn, &QPushButton::clicked, this, &MainWindow::prevPlayer);
    connect(playBtn, &QPushButton::clicked, this, &MainWindow::startPlayer);
    connect(nextBtn, &QPushButton::clicked, this, &MainWindow::nextPlayer);

    connect(playProgress, &QSlider::valueChanged, this, &MainWindow::valueChange);
    connect(playProgress, &QSlider::sliderMoved, this, &MainWindow::sliderMove);

    connect(mediaPlayer, &QMediaPlayer::durationChanged, this, &MainWindow::durationChange);
    connect(mediaPlayer, &QMediaPlayer::positionChanged, this, &MainWindow::positionChange);

    connect(mediaPlaylist, &QMediaPlaylist::currentIndexChanged, this, &MainWindow::currentIndexChange);

    connect(timer, &QTimer::timeout, this, &MainWindow::timerout);
}

void MainWindow::initMedia()
{
    mediaPlayer = new QMediaPlayer(this);
    mediaPlaylist = new QMediaPlaylist(this);
    mediaPlayer->setPlaylist(mediaPlaylist);
    mediaPlayer->setVideoOutput(videoWidget);
    mediaPlaylist->clear();
    mediaPlaylist->setPlaybackMode(QMediaPlaylist::Loop);
}

void MainWindow::scanMedia()
{
#if __arm__
    QDir dir(R"(/userdata/media)");
#else
    QDir dir(R"(D:\Desktop\video)");
#endif

    QDir dirbsolutePath(dir.absolutePath());

    if (!dirbsolutePath.exists()) {
        qDebug() << dir << endl;
        return;
    }

    qDebug() << __LINE__ << dir << endl;
    qDebug() << __LINE__ << dirbsolutePath << endl;

    QStringList filter;
    filter << "*.mp3" << "*.wav" << "*.mp4" << "*.mkv";
    QFileInfoList files = dirbsolutePath.entryInfoList(filter, QDir::Files);
    listWidget->clear();
    for(int i = 0; i < files.count(); i++) {
        QString filePath = files.at(i).filePath();
        if (mediaPlaylist->addMedia(QUrl::fromLocalFile(filePath))) {
            listWidget->addItem(files.at(i).fileName());
            qDebug() << "info.fileName" << filePath << endl;
        } else {
            qDebug() << "Error filePath" << filePath << endl;
            qDebug() << mediaPlaylist->errorString().toUtf8().data() << endl;
            qDebug() << "Error number:" << mediaPlaylist->error() << endl;
        }
    }
}

void MainWindow::fullPlayer()
{
    videoWidget->setWindowFlags(Qt::Window);
    videoWidget->showFullScreen();
}

void MainWindow::prevPlayer()
{
    mediaPlaylist->previous();
    mediaPlayer->play();
}

void MainWindow::startPlayer()
{
    auto state = mediaPlayer->state();
    switch(state) {
    case QMediaPlayer::StoppedState: {
        mediaPlayer->play();
    } break;
    case QMediaPlayer::PlayingState: {
        mediaPlayer->pause();
    } break;
    case QMediaPlayer::PausedState: {
        mediaPlayer->play();
    } break;
    }
}

void MainWindow::nextPlayer()
{
    mediaPlaylist->next();
    mediaPlayer->play();
}

void MainWindow::durationChange(quint64 duration)
{
    qDebug() << "duration = " << duration << endl;
    playProgress->setRange(0, static_cast<int>(duration / 1000));
}

void MainWindow::positionChange(quint64 position)
{
    qDebug() << "position = " << position << endl;
    playProgress->setSliderPosition(static_cast<int>(position / 1000));
}

void MainWindow::valueChange(int value)
{
    qDebug() << "sliderMoved:value = " << value << endl;
}

void MainWindow::sliderMove(int position)
{
    qDebug() << "sliderMoved:position = " << position << endl;
}

void MainWindow::currentIndexChange(int index)
{
    qDebug() << index << endl;
    if (index >= 0) {
        listWidget->setVisible(true);
        listWidget->setCurrentRow(index);
        timer->start(1000);
    }
}

void MainWindow::timerout()
{
    timer->stop();
    listWidget->setVisible(false);
}
